package com.xingkeduo.service.api.marketing.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xingkeduo.dao.TActivityDaysMapper;
import com.xingkeduo.dao.TMarketingCardMapper;
import com.xingkeduo.dao.TMarketingReceiveHistoryCardMapper;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.model.example.TActivityDaysExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample;
import com.xingkeduo.model.example.TMarketingReceiveHistoryCardExample.Criteria;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveStatusEnum;
import com.xingkeduo.model.po.TActivityDays;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingReceiveHistory;
import com.xingkeduo.model.po.TMarketingReceiveHistoryCard;
import com.xingkeduo.model.vo.ActivityDaysResponseVo;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.model.vo.ReceiveHistoryResponseVo;
import com.xingkeduo.service.api.marketing.CardService;
import com.xingkeduo.service.consume.UserService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class CardServiceImpl implements CardService {
	Logger logger = LoggerFactory.getLogger(CardServiceImpl.class);

	@Autowired
	TMarketingReceiveHistoryCardMapper tMarketingReceiveHistoryCardMapper;
	@Autowired
	TMarketingCardMapper tMarketingCardMapper;
	@Autowired
	TActivityDaysMapper tActivityDaysMapper;
	@Autowired
	ManageUserFeignService manageUserFeignService;
	@Autowired
	UserService userService;
	@Override
	public ResponseMessage queryCardByTemplate(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {

		List<Long> userList = userService.queryUserIdsByUserId(marketingReceiveHistoryParam.getUserId());
		TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
		Criteria criteria = example.createCriteria();
		if (CollectionUtils.isNotEmpty(userList)) {
			criteria.andUserIdIn(userList);
		} else {
			criteria.andUserIdEqualTo(marketingReceiveHistoryParam.getUserId());
		}
		criteria.andMarketingTypeEqualTo(marketingReceiveHistoryParam.getMarketingType());
		// 已过期
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.EXPIRED.getCode()) {
			criteria.andStatusIn(Lists.newArrayList(MarketingReceiveStatusEnum.AVAILABLE.getCode(),
					MarketingReceiveStatusEnum.EXPIRED.getCode())).andUseEndTimeLessThan(new Date());
		}
		// 不可用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.UNAVAILABLE.getCode()) {
			criteria.andStatusNotIn(Lists.newArrayList(MarketingReceiveStatusEnum.AVAILABLE.getCode(),
					MarketingReceiveStatusEnum.USED.getCode()));
		}
		// 可使用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.AVAILABLE.getCode()) {
			criteria.andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
					.andUseEndTimeGreaterThan(new Date());
		}
		// 已使用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.USED.getCode()) {
			criteria.andStatusEqualTo(MarketingReceiveStatusEnum.USED.getCode());
		}
		example.setOrderByClause("id desc");
		List<ReceiveHistoryResponseVo> historyListVo = new ArrayList<ReceiveHistoryResponseVo>();
		// 查询领取记录
		PageHelper.startPage(marketingReceiveHistoryParam.getPageNum(), marketingReceiveHistoryParam.getPageSize());
		List<TMarketingReceiveHistoryCard> historyList = tMarketingReceiveHistoryCardMapper
				.selectByExample(example);
		PageInfo<TMarketingReceiveHistoryCard> page = new PageInfo<>(historyList);
		// 对领取记录赋值卡，券信息。
		for (TMarketingReceiveHistory tMarketingReceiveHistory : historyList) {
			ReceiveHistoryResponseVo vo = new ReceiveHistoryResponseVo();
			BeanUtils.copyProperties(tMarketingReceiveHistory, vo);
			if (tMarketingReceiveHistory.getMarketingId() != null) {
				TMarketing marketing = tMarketingCardMapper
						.selectByPrimaryKey(tMarketingReceiveHistory.getMarketingId());
				vo.setStoreNames(marketing.getStoreNames());
				MarketingResponseVo re = new MarketingResponseVo();
				BeanUtils.copyProperties(marketing, re);
				TActivityDaysExample daysexample = new TActivityDaysExample();
				daysexample.createCriteria().andActivityIdEqualTo(marketing.getId())
						.andStatusEqualTo(Constant.STATUS_YES)
						.andActivityTypeEqualTo(marketing.getMarketingType());
				daysexample.setOrderByClause(" dayids desc");
				// 卡券活动时间
				List<TActivityDays> days = tActivityDaysMapper.selectByExample(daysexample);
				List<ActivityDaysResponseVo> daysVo = new ArrayList<ActivityDaysResponseVo>();
				for (TActivityDays day : days) {
					ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
					BeanUtils.copyProperties(day, activityDaysResponseVo);
					daysVo.add(activityDaysResponseVo);
				}
				// 卡券添加活动时间
				re.setActivityDays(daysVo);
				vo.setMarketingInfo(re);
			}
			historyListVo.add(vo);
		}

		PageInfo<ReceiveHistoryResponseVo> pageReturn = new PageInfo<>();
		BeanUtils.copyProperties(page, pageReturn);
		pageReturn.setList(historyListVo);
		return ResponseMessage.ok(pageReturn);
	}

	@Override
	public ResponseMessage queryCardDetailByTemplate(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		// 领取记录
		TMarketingReceiveHistory history = tMarketingReceiveHistoryCardMapper
				.selectByPrimaryKey(marketingReceiveHistoryParam.getId());
		ReceiveHistoryResponseVo vo = new ReceiveHistoryResponseVo();
		BeanUtils.copyProperties(history, vo);
		if (history.getMarketingId() != null) {
			// 卡，券信息
			TMarketing makrting = tMarketingCardMapper.selectByPrimaryKey(history.getMarketingId());
			MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
			BeanUtils.copyProperties(makrting, marketingResponseVO);
			if(StringUtils.isNotBlank(marketingResponseVO.getStoreIds())) {
				String storeIds = marketingResponseVO.getStoreIds();
				if(storeIds.startsWith("0,")) {
					storeIds = storeIds.substring(2, storeIds.length());
				}
				if(storeIds.endsWith(",0")) {
					storeIds = storeIds.substring(0, storeIds.length()-2);
				}
				marketingResponseVO.setStoreIds(storeIds);
			}
			TActivityDaysExample example = new TActivityDaysExample();
			example.createCriteria().andActivityIdEqualTo(makrting.getId())
					.andStatusEqualTo(Constant.STATUS_YES)
					.andActivityTypeEqualTo(history.getMarketingType());
			example.setOrderByClause(" dayids desc");
			// 卡券活动时间
			List<TActivityDays> days = tActivityDaysMapper.selectByExample(example);
			List<ActivityDaysResponseVo> daysVo = new ArrayList<ActivityDaysResponseVo>();
			for (TActivityDays day : days) {
				ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
				BeanUtils.copyProperties(day, activityDaysResponseVo);
				daysVo.add(activityDaysResponseVo);
			}
			// 卡券添加活动时间
			marketingResponseVO.setActivityDays(daysVo);
			// 领取记录添加卡，券信息
			vo.setMarketingInfo(marketingResponseVO);
			vo.setStoreNames(makrting.getStoreNames());
		}
		return ResponseMessage.ok(vo);

	}

	@Override
	public ResponseMessage queryCardByTemplateNoPage(MarketingReceiveHistoryParam marketingReceiveHistoryParam) {
		List<Long> userList = userService.queryUserIdsByUserId(marketingReceiveHistoryParam.getUserId());
		TMarketingReceiveHistoryCardExample example = new TMarketingReceiveHistoryCardExample();
		Criteria criteria = example.createCriteria();
		if (CollectionUtils.isNotEmpty(userList)) {
			criteria.andUserIdIn(userList);
		} else {
			criteria.andUserIdEqualTo(marketingReceiveHistoryParam.getUserId());
		}
		criteria.andMarketingTypeEqualTo(marketingReceiveHistoryParam.getMarketingType());
		// 已过期
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.EXPIRED.getCode()) {
			criteria.andStatusIn(Lists.newArrayList(MarketingReceiveStatusEnum.AVAILABLE.getCode(),
					MarketingReceiveStatusEnum.EXPIRED.getCode())).andUseEndTimeLessThan(new Date());
		}
		// 不可用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.UNAVAILABLE.getCode()) {
			criteria.andStatusNotIn(Lists.newArrayList(MarketingReceiveStatusEnum.AVAILABLE.getCode(),
					MarketingReceiveStatusEnum.USED.getCode()));
		}
		// 可使用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.AVAILABLE.getCode()) {
			criteria.andStatusEqualTo(MarketingReceiveStatusEnum.AVAILABLE.getCode())
					.andUseEndTimeGreaterThan(new Date());
		}
		// 已使用
		if (marketingReceiveHistoryParam.getStatus().intValue() == MarketingReceiveStatusEnum.USED.getCode()) {
			criteria.andStatusEqualTo(MarketingReceiveStatusEnum.USED.getCode());
		}
		example.setOrderByClause("id desc");
		List<ReceiveHistoryResponseVo> historyListVo = new ArrayList<ReceiveHistoryResponseVo>();
		// 查询领取记录
		List<TMarketingReceiveHistoryCard> historyList = tMarketingReceiveHistoryCardMapper
				.selectByExample(example);
		// 对领取记录赋值卡，券信息。
		for (TMarketingReceiveHistory tMarketingReceiveHistory : historyList) {
			ReceiveHistoryResponseVo vo = new ReceiveHistoryResponseVo();
			BeanUtils.copyProperties(tMarketingReceiveHistory, vo);
			if (tMarketingReceiveHistory.getMarketingId() != null) {
				TMarketing marketing = tMarketingCardMapper
						.selectByPrimaryKey(tMarketingReceiveHistory.getMarketingId());
				if(marketing==null) {
					continue;
				}
				vo.setStoreNames(marketing.getStoreNames());
				MarketingResponseVo re = new MarketingResponseVo();
				BeanUtils.copyProperties(marketing, re);
				TActivityDaysExample daysexample = new TActivityDaysExample();
				daysexample.createCriteria().andActivityIdEqualTo(marketing.getId())
						.andStatusEqualTo(Constant.STATUS_YES)
						.andActivityTypeEqualTo(marketing.getMarketingType());
				daysexample.setOrderByClause(" dayids desc");
				// 卡券活动时间
				List<TActivityDays> days = tActivityDaysMapper.selectByExample(daysexample);
				List<ActivityDaysResponseVo> daysVo = new ArrayList<ActivityDaysResponseVo>();
				for (TActivityDays day : days) {
					ActivityDaysResponseVo activityDaysResponseVo = new ActivityDaysResponseVo();
					BeanUtils.copyProperties(day, activityDaysResponseVo);
					daysVo.add(activityDaysResponseVo);
				}
				// 卡券添加活动时间
				re.setActivityDays(daysVo);
				vo.setMarketingInfo(re);
			}
			historyListVo.add(vo);
		}
		return ResponseMessage.ok(historyListVo);
	}

}
